package com.wrx.swing.menu;

import javax.swing.*;
import java.awt.*;
import java.util.function.Supplier;

/**
 * 菜单栏构建工具类
 */
public final class MenuBarFactory {

    private MenuBarFactory() {
    }

    /**
     * 创建菜单栏并设置到窗口上
     */
    public static void attachToFrame(JFrame frame, Supplier<CardLayout> cardLayoutSupplier, Supplier<JPanel> mainPanelSupplier) {
        JMenuBar menuBar = createMenuBar(frame, cardLayoutSupplier, mainPanelSupplier);
        frame.setJMenuBar(menuBar);
    }

    private static JMenuBar createMenuBar(JFrame frame, Supplier<CardLayout> cardLayoutSupplier, Supplier<JPanel> mainPanelSupplier) {
        JMenuBar menuBar = new JMenuBar();
        for (MenuConfig menuGroup : MenuConfig.getAllGroups()) {
            JMenu menu = createMenu(menuGroup, frame, cardLayoutSupplier, mainPanelSupplier);
            menuBar.add(menu);
        }
        return menuBar;
    }

    private static JMenu createMenu(MenuConfig menuConfig, JFrame frame, Supplier<CardLayout> cardLayoutSupplier, Supplier<JPanel> mainPanelSupplier) {
        JMenu menu = new JMenu(menuConfig.getDisplayName());
        if (menuConfig.getChildren() != null) {
            for (MenuConfig child : menuConfig.getChildren()) {
                JMenuItem menuItem = createMenuItem(child, frame, cardLayoutSupplier, mainPanelSupplier);
                menu.add(menuItem);
            }
        }
        return menu;
    }

    private static JMenuItem createMenuItem(MenuConfig menuConfig, JFrame frame, Supplier<CardLayout> cardLayoutSupplier, Supplier<JPanel> mainPanelSupplier) {
        JMenuItem item = new JMenuItem(menuConfig.getDisplayName());
        item.addActionListener(e -> {
            CardLayout cardLayout = cardLayoutSupplier.get();
            JPanel mainPanel = mainPanelSupplier.get();
            if (cardLayout != null && mainPanel != null) {
                cardLayout.show(mainPanel, menuConfig.getCardName());
            }
            frame.setTitle(menuConfig.getTitle());
        });
        return item;
    }
}
